package com.wh.wisdomsite.xbox.server.listener;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wh.wisdomsite.xbox.ba.entity.XboxLog;
import com.wh.wisdomsite.xbox.ba.service.IXboxLogService;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.XboxRequestContext;
import com.wh.wisdomsite.xbox.core.event.AfterDoServiceEvent;
import com.wh.wisdomsite.xbox.core.event.XboxEventListener;
import com.wh.wisdomsite.xbox.core.SessionUser;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.json.FormatJsonUtil;
import com.jiangshikun.parrot.dao.RedisBaseDao;
import com.jiangshikun.parrot.dao.StringDao;
import java.sql.Timestamp;

/***
 * 日志监听器
 * @Package com.wh.wisdomsite.xbox.server.listener
 * @author 谢泽鹏
 * @date 2016年11月07日 下午15:10
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
public class InvokeLogEventListener implements XboxEventListener<AfterDoServiceEvent> {

    private IXboxLogService xboxLogService;

    public IXboxLogService getXboxLogService() {
        return xboxLogService;
    }

    public void setXboxLogService(IXboxLogService xboxLogService) {
        this.xboxLogService = xboxLogService;
    }

    private StringDao stringDao = RedisBaseDao.getStringDao();

    @Override
    public void handleEvent(AfterDoServiceEvent event) {
        //获取xboxRequestContext对象
        XboxRequestContext xboxRequestContext = event.getXboxRequestContext();
        //创建主日志对象
        XboxLog xboxLog = new XboxLog();
        //设置:应用Key
        xboxLog.setAppKey(xboxRequestContext.getAppKey());
        //设置:服务方法
        xboxLog.setMethod(xboxRequestContext.getMethod());
        //设置:服务版本
        xboxLog.setVersion(xboxRequestContext.getVersion());
        //设置:语言方式[zh_CN, en]
        xboxLog.setLocale(xboxRequestContext.getLocale().toString());
        //设置:调用方式[SYNC, ASYNC]
        xboxLog.setExecutionType(xboxRequestContext.getExecutionType());
        //设置:请求方式[POST, GET]
        xboxLog.setHttpAction(xboxRequestContext.getHttpAction().toString());
        //设置:数据格式[json, xml]
        xboxLog.setFormat(xboxRequestContext.getFormat());
        //设置:sign签名
        xboxLog.setSign(xboxRequestContext.getSign());
        //设置:执行耗时[请求开始时间 - 请求结束时间](单位毫秒)
        xboxLog.setDuration(String.valueOf(xboxRequestContext.getDuration()));
        //设置:客户端真实IP
        xboxLog.setIp(xboxRequestContext.getIp());
        //设置:业务参数(美化JSON输出)
        xboxLog.setBindObject(FormatJsonUtil.formatJson(xboxRequestContext.getBindObject()));
        //设置:响应结果
        xboxLog.setOutput(xboxRequestContext.getOutPut());
        //设置:替换password中的明文密码
//        if (xboxLog.getFormat().equals(MessageFormat.json.toString())){
//            String passKey = "\"password\":\"";
//            if(null != xboxLog.getBindObject()){
//                int passwordIndex = xboxLog.getBindObject().indexOf(passKey);
//                if (passwordIndex >= 0) {
//                    int nextColonIndex = xboxLog.getBindObject().indexOf("\"", passwordIndex + passKey.length());
//                    xboxLog.setBindObject(xboxLog.getBindObject().substring(0, passwordIndex + passKey.length())
//                            + "******" + xboxLog.getBindObject().substring(nextColonIndex));
//                }
//            }
//        }
        //设置:异常信息
        xboxLog.setException(xboxRequestContext.getException());
        //获取:服务配置是否需要会话
        //boolean needInSession = xboxRequestContext.getXboxContext().getServiceMthodHandler(xboxRequestContext.getMethod(), xboxRequestContext.getVersion()).getServiceMethodDefinition().isNeedInSession();
        //判断:是否需要会话
        //if(needInSession){
            //获取:会话标识
            String sessionId = xboxRequestContext.getSessionId();
            //设置:用户属性
            if(StringUtils.isNotEmpty(sessionId)){
                //获取缓存JSONObject
                JSONObject jsonObject = JSON.parseObject(stringDao.getValue(Constants.ReadisKey + sessionId));
                if(null != jsonObject){
                    JSONObject jsonAttributes = (JSONObject) jsonObject.get("attributes");
                    if(null != jsonAttributes){
                        JSONObject jsonSessionUser = (JSONObject) jsonAttributes.get(Constants.SESSION_USER);
                        if(null != jsonSessionUser){
                            SessionUser sessionUser = JSON.parseObject(jsonSessionUser.toJSONString(), SessionUser.class);
                            if(null != sessionUser){
                                //设置:会话标识
                                xboxLog.setSessionId(sessionId);
                                //设置:用户编号
                                xboxLog.setSessionUserId(sessionUser.getUserId() + "");
                                //设置:手机号码
                                xboxLog.setSessionPhone(sessionUser.getPhone() + "");
                                //设置:会话用户
                                xboxLog.setSessionUserName(sessionUser.getUserName() + "");
                            }
                        }
                    }
                }
            }
        //}
        //设置:执行结果[1:成功, 0:失败]
        xboxLog.setExecuteStatus(xboxRequestContext.isSuccess() ? 1 : 0);
        //设置:应用类型
        xboxLog.setCallType(xboxRequestContext.getCallType());
        //设置:应用版本
        xboxLog.setCallVersion(xboxRequestContext.getCallVersion());
        //设置:系统平台
        xboxLog.setClient(xboxRequestContext.getClient());
        //设置:应用品牌
        xboxLog.setAppBrand(xboxRequestContext.getAppBrand());
        //设置:应用信息(美化JSON输出)
        xboxLog.setAppBaseInfo(FormatJsonUtil.formatJson(xboxRequestContext.getAppBaseInfo()));
        //设置:请求开始时间
        xboxLog.setCreateDate(new Timestamp(xboxRequestContext.getBeginTime()));
        //设置:请求结束时间
        xboxLog.setUpdateDate(new Timestamp(xboxRequestContext.getEndTime()));
        //声明:响应编码
        String serviceCode = null;
        //声明:响应消息
        String serviceMessage = null;
        //获取:响应对象
        if(StringUtils.isNotEmpty(xboxRequestContext.getOutPut())){
            //判断：响应对象
            JSONObject jsonObject = JSON.parseObject(xboxRequestContext.getOutPut());
            if(null != jsonObject){
                serviceCode = StringUtils.isNotEmpty(jsonObject.get("code") + "") ? jsonObject.get("code") + "" : "";
                serviceMessage = StringUtils.isNotEmpty(jsonObject.get("message") + "") ? jsonObject.get("message") + "" : "";
            }
        }
        //设置:响应编码
        xboxLog.setServiceCode(serviceCode);
        //设置:响应消息
        xboxLog.setServiceMessage(serviceMessage);

        if("wh.test.testCase".equalsIgnoreCase(xboxRequestContext.getMethod()) || "wh.test.testGetLocationCity".equalsIgnoreCase(xboxRequestContext.getMethod())){

        }else{
            //保存:操作日志
            xboxLogService.save(xboxLog);
        }


     }



    @Override
    public int getOrder() {
        return 1;
    }
}

